// -----------------------------------------------------------------------------
// This source file is part of Matrix Platform
// 	(Universal .NET Software Development Platform)
// For the latest info, see http://www.matrixplatform.com
// 
// Copyright (c) 2009-2010, Ingenious Ltd
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Matrix.Common.Diagnostics;

namespace Matrix.Common.FrontEnd
{
    /// <summary>
    /// 
    /// </summary>
    internal class MethodInvocationInformation
    {
        DateTime _lastInvocation = DateTime.MinValue;

        volatile bool _isCallPending = false;

        public bool IsCallCompleted
        {
            get
            {
                if (_currentExecutionResult != null && _currentExecutionResult.IsCompleted == false)
                {
                    return false;
                }

                return true;
            }
        }

        object[] _lastInvocationParameters = null;

        TimeSpan _minimumCallInterval = TimeSpan.MaxValue;

        Control _control = null;

        Delegate _delegate = null;

        IAsyncResult _currentExecutionResult = null;

        /// <summary>
        /// 
        /// </summary>
        protected bool LastInvocationTimedOut
        {
            get
            {
                lock (this)
                {
                    return (DateTime.Now - _lastInvocation) >= _minimumCallInterval;
                }
            }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public MethodInvocationInformation(Control control, Delegate d)
        {
            _control = control;
            _delegate = d;
        }

        /// <summary>
        /// Invoked by the timer based invocation monitor, allows to execute pending calls, after a time interval has passed.
        /// </summary>
        public void CheckCall()
        {
            lock (this)
            {
                if (_isCallPending == false || LastInvocationTimedOut == false)
                {// No call pending, or last invocation too soon.
                    return;
                }
            }

            Invoke(TimeSpan.MaxValue, _lastInvocationParameters);
        }

        /// <summary>
        /// Submit an invoke request, if currently an invoke is done, this will be put as pending.
        /// </summary>
        public bool Invoke(TimeSpan minimumCallInterval, params object[] parameters)
        {
            bool lastInvocationTimedOut = LastInvocationTimedOut;
            //bool isCallPending = _isCallPending;
            lock (this)
            {
                if ((_currentExecutionResult != null && _currentExecutionResult.IsCompleted == false)
                    || (/*_isCallPending && */lastInvocationTimedOut == false))
                {// Current call in progress, or a call already pending and not time for execution yet.

                    //SystemMonitor.Info("Performing managed invoke...: *MISSED* " + _delegate.Target.ToString() + "." +
                    //    _delegate.Method.Name + " " + lastInvocationTimedOut.ToString() + " " + isCallPending);

                    _isCallPending = true;
                    _lastInvocationParameters = parameters;
                    _minimumCallInterval = TimeSpan.FromMilliseconds(System.Math.Min(minimumCallInterval.TotalMilliseconds, _minimumCallInterval.TotalMilliseconds));

                    return false;
                }

                _isCallPending = false;
                _lastInvocationParameters = null;
                _lastInvocation = DateTime.Now;

                // Reset the minimum call interval.
                _minimumCallInterval = TimeSpan.MaxValue;
            }

            // Make sure to do this outside of lock, since it may cause a deadlock.
            _currentExecutionResult = WinFormsHelper.BeginManagedInvoke(_control, _delegate, parameters);

            //SystemMonitor.Info("Performing managed invoke...: " + _delegate.Target.ToString() + "." +
            //    _delegate.Method.Name + " " + lastInvocationTimedOut.ToString() + " " + isCallPending);

            return true;
        }
    }
}
